package org.rqb.config;

import org.rqb.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.io.*;
import java.nio.file.*;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyConfig {

    private static final Logger log = LoggerFactory.getLogger(MyConfig.class);
    private static Properties config;

    public static Properties getConfig() {
        if (config == null) {
            config = new Properties();
            File configFile = new File(Constant.WORK_DIR + "\\config.properties");

            // 如果配置文件不存在，复制 resource 下的 config.properties
            if (!configFile.exists()) {
                try (InputStream resourceStream = MyConfig.class.getClassLoader().getResourceAsStream("config.properties")) {
                    if (resourceStream == null) {
                        throw new FileNotFoundException("无法在资源目录中找到 config.properties 文件");
                    }

                    // 将资源文件复制到工作目录
                    Files.copy(resourceStream, configFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    throw new RuntimeException("无法复制资源文件到工作目录", e);
                }
            }

            // 加载工作目录中的配置文件
            try (InputStream inputStream = new FileInputStream(configFile)) {
                config.load(inputStream);
                log.info("配置加载成功");
            } catch (IOException e) {
                throw new RuntimeException("加载工作目录中的 config.properties 文件失败", e);
            }
        }
        return config;
    }

    public static void updateConfig(Map<String, String> map) {
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() {
                Set<Map.Entry<String, String>> entries = map.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    config.setProperty(key, value);
                }

                // 更新工作目录中的配置文件
                try (FileOutputStream output = new FileOutputStream(Constant.WORK_DIR + "\\config.properties")) {
                    config.store(output, "更新配置");
                    log.info("配置更新成功");

                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

        };
        worker.execute();


    }

}
